#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;

// char *Hex(pthread_t tid)
// {
//     static char tmp[30];
//     snprintf(tmp, sizeof(tmp), "0X%x", tid);
//     return tmp;
// }
// void *ThreadRoutine(void *arg)
// {
//     const char *threadname = (const char *)arg;
//     while (true)
//     {
//         cout << "I am a new thread: " << threadname << endl;
//         sleep(1);
//         break;
//     }
//     static char tmp[60]; // 局部变量出栈就会销毁，设为静态
//     snprintf(tmp, sizeof(tmp), "i have done:%s", threadname);
//     pthread_exit((void *)tmp);
// }

int g_val = 1000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *ThreadRoutine(void *args)
{
    string name = static_cast<const char *>(args);
    while (1)
    {
        pthread_mutex_lock(&mutex);//对临界区加锁
        if (g_val > 0)
        {
            usleep(1000); //
            cout << "i am a new thread:" << name << " g_val = " << g_val << endl;
            g_val--;
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
}
int main()
{
    // 已经有进程了
    pthread_t tid_1, tid_2, tid_3;
    pthread_create(&tid_1, nullptr, ThreadRoutine, (void *)"thread_1");
    pthread_create(&tid_2, nullptr, ThreadRoutine, (void *)"thread_2");
    pthread_create(&tid_3, nullptr, ThreadRoutine, (void *)"thread_3");

    // 线程等待

    pthread_join(tid_1, nullptr);
    pthread_join(tid_2, nullptr);
    pthread_join(tid_3, nullptr);

    return 0;
}